#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# Restricted Materials of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2002,2003 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
####################################################################
#
#   lsswtrace command
#
#   Syntax:  lsswtrace [ [ --all | -F <format> ] [ -f <input_filename> ] 
#                             | --help ] 
#
#            --help               - Prints this message
#            --all                   - Used to indicate that the user wants
#                                 to see all columns of data poreceded
#                                 by a header, instead of just the 
#                                 default ones, which are:
#                                      time
#                                      appl_name
#                                      details
#                                      network
#                                      plane
#                                      type
#                                      chip
#                                      port
#                                      message
#            -F <"format">        - a delimiter separated list of names
#                                 representing desired trace fields to
#                                 view. Valid values are:
#                                      time
#                                      appl_name
#                                      level
#                                      details
#                                      network
#                                      plane
#                                      type
#                                      frame
#                                      slot
#                                      chip
#                                      port
#                                      log_time
#                                      sw_tod
#                                      bpa_time
#                                      host_name
#                                      file_name
#                                      file_ver
#                                      line_num
#                                      message
#                                      raw_data
#                          If -F is not specified, all columns are shown.
#            -f <input_filename>  - specifies a filename from where
#                                 trace data is to come, rather than
#                                 "live" trace data on the HMC
#
####################################################################
#
#   Initial version - 09/06/02
#
####################################################################

use Getopt::Long;

sub bynumber { $a <=> $b; }

sub exit_routine {
    
     # remove files from /tmp 
     
     exit $ret; 

} # end exit_routine subroutine

################################################################################
#
# subroutines to parse properties desired (-F parm)
#
################################################################################
sub parse_props {
	$parm_length = length($props_parm);
	if (substr($props_parm,0,1) eq ":") {
                        # There was a colon at the beginning
			#      of the -F value
#			print "Colon in the beginning\n";   #DEBUG
			print $USAGE;    #USAGE
			$ret = 1;
			&exit_routine;
	}

	if (substr($props_parm,$parm_length-1) ne ":") {
                        # There was not a colon at the end
			#      of the -F value
#			print "No colon at the end\n";   #DEBUG
			print $USAGE;    #USAGE
			$ret = 1;
			&exit_routine;
	}

#	($p1,$p2,$p3,$p4,$p5,$p6,$p7,$p8,$9) = split /:/, $props_parm, 9;

	# Find number of colons used
	$NUM_COLONS = 0;
	while ($props_parm =~ m/:/g) {
		$NUM_COLONS += 1;
	}

	@prop_list = split /:/, $props_parm, $MAX_PROPS + 1;

	# Now examine fields passed
        for ($i = 0; $i < $NUM_COLONS; $i++) {
		$prop = $prop_list[$i];
		# Were the fields specified properly?
		if ($prop eq "") {
#			print "There was a NULL field passed.\n";   #DEBUG
			print $USAGE;    #USAGE
			$ret = 1;
			&exit_routine;
		}
		else {
			# Is this a valid field name?
			$FOUND = 0;
			for ($j = 0; $j < $MAX_PROPS; $j++) {
				if ($prop eq $DEF_PROPS[$j]) {
					if ($FOUND_PROPS[$j] == 1) {
						# Second time for this prop
#						print "SECOND time\n"; #DEBUG
						print $USAGE;
						&exit_routine;
					}
					else {
						$FOUND = 1;
						$FOUND_PROPS[$j] = 1;
						$ORDER[$NUM_PROPS] = $j;
						$cols_int = $cols_int | @HEX_BIT[$j];
					}
				}
			}

			# Was the field name a valid field name?
			if ($FOUND == 0) {
#				print "Field name NOT found\n";     #DEBUG
				print $USAGE;
				$ret = 1;
				&exit_routine;
			}

			$NUM_PROPS += 1;
			
#			# Were an incorrect number of fields passed?
#		        if ($NUM_PROPS > $MAX_PROPS) {
#				print "Too MANY props passed\n";        #DEBUG
#				print $USAGE;
#			}
		}
	}
}


################################################################################
#
# credentials subroutines
#
################################################################################
sub remove_creds {
        system "/bin/rm $RCMDTKFILE > /dev/null 2>&1";
        if ($DCE_tickets == 1) {
                `/bin/kdestroy`;
                 delete $ENV{'KRB5CCNAME'};
        }
} # end remove_creds subroutine

################################################################################
#
# start main body of code
#
################################################################################
$PRGRM  = "lsswtrace";
$BIN    = "/opt/hsc/bin"; 
$PARMS = 0;
$file_op = "";

$USAGE = "Usage: lsswtrace [ [ --all | -F <format> ] [ -f <input_filename> ] \
                             | --help ]\n";
$NUM_PROPS = 0;
$DEF_PROPS = 9;
$MAX_PROPS = 20;
@DEF_PROPS = ("time" , "level" , "appl_name" , "details" , "network" , "plane" , "type" , "frame" , "slot" , "chip" , "port" , "log_time" , "sw_tod" , "bpa_time" , "host_name" , "file_name" , "file_ver" , "line_num" , "message" , "raw_data");
@FOUND_PROPS = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
@HEAD = ("              time ", "        level ", "       appl_name ", "              details ", " network ", " plane ", " type ", " frame ", "  slot ", " chip " ," port ", "          log_time ", " sw_tod ", "          bpa_time ", "                 host_name ", "                                                                                   file_name ", "  file_ver ", " line_num ", " message ", " raw_data ");
@FORMAT = (" %17s ", " %12s ", " %15s ", " %20s ", " %7s ", " %5s ", " %4s ", " %4s ", " %4s ", " %4s ", " %4s ", " %17s ", " %7s ", " %17s ", " %25s ", " %75s ", " %9s ", " %8s ", " %75s ", " %7s ");
@HEX_BIT = (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288);
$cols_int = 0;

$BLANK_SEP_COLS = 19;    # There are 18 columns before the message column which are separated by white space
$MSG_COL = 18;           # The message column is the 18th in the data returned, using a zero-index numbering.
$RAW_DATA_COL = 19;      # The raw data is in the 19th spot in the data returned, using a zero-index numbering.

# First check for existence of parameters
if ($#ARGV ne -1) {
	$PARMS = 1;
}

# If there are parms, need to validate and parse
if ($PARMS == 1) {

	Getopt::Long::Configure("no_ignore_case");
	$result = GetOptions(
		"all" => \$all,
	        "help" => \$help,
	        "F=s" => \$Format,
	        "f=s" => \$file
	);

#print "GetOptions rc is ", $result, " .\n";

	if ($result == 0) {
		# Bad result from GetOptions
#		print "Bad result from GetOptions\n";     #DEBUG
		print $USAGE;      #USAGE
		$ret = 1;
		&exit_routine;
	}

	if ($help) {
		# help was asked for
#		print "help was specified\n";     #DEBUG
		print $USAGE;      #USAGE
		$ret = 0;
		&exit_routine;
	}

	$props_parm = $Format;  # colon-separated list of column names

	$file_parm = $file;  # alternate trace file specification

        if ((defined $Format) && (defined $all)) {
		# Specified both --all and -F
#		print "-F and --all both used\n";     #DEBUG
		print $USAGE;      #USAGE
		$ret = 1;
		&exit_routine;
	}

	if ($props_parm ne "") {
		&parse_props;
	}
	else {
		if (defined $Format) { 
			# Nothing else was specified after -F
#			print "Nothing after -F -- shouldn't get here\n";     #DEBUG
			print $USAGE;      #USAGE
			$ret = 1;
			&exit_routine;
		}
	}

	if ($file_parm ne "") {
		if (!(-e $file_parm)) {
			# File does not exist
#			print "File after -f does not exist\n";     #DEBUG
                        print $USAGE;      #USAGE
                        $ret = 1;
                        &exit_routine;
                }
		if (!(-r $file_parm)) {
			# File is not readable
#			print "File after -f is not readable\n";     #DEBUG
                        print $USAGE;      #USAGE
                        $ret = 1;
                        &exit_routine;
                }
		$file_op = "-file ".$file_parm;
	}
	else {
		if (defined $file) { 
			# Nothing else was specified after -f
#			print "Nothing after -f -- shouldn't get here\n";     #DEBUG
			print $USAGE;      #USAGE
			$ret = 1;
			&exit_routine;
		}
	}
}

if (not defined $Format) {
	if (defined $all) {
		# -F was not specified but --all was, so use all
		$NUM_PROPS = $MAX_PROPS;
        	@FOUND_PROPS = (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
	        @ORDER = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19);
        	$cols_int = 1048575;
	}
	else {
		# No -F or --all so use defaults
		$NUM_PROPS = $DEF_PROPS;
        	@FOUND_PROPS = (1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0);
	        @ORDER = (0, 2, 3, 4, 5, 6, 9, 10, 18);
        	$cols_int = 263805;
	}
}

$cols_hex = sprintf "%1x", $cols_int;
# Now let's get all the data
#chop(@DATA = `CLASSPATH=/usr/websm/codebase/wsm.jar:/opt/hsc java com.ibm.hsc.auiml.databeans.snm.SnmInfo trview -columns FFFFF $file_op`);
chop(@DATA = `CLASSPATH=/usr/websm/codebase/pluginjars/SNMGUI.jar:/usr/websm/codebase/wsm.jar:/usr/websm/codebase/pluginjars/hsc.jar java com.ibm.hsc.auiml.databeans.snm.SnmInfo trview -columns FFFFF $file_op`);

if ($DATA[0] eq 0) {
#	print "SnmInfo returned 0.\n";             #DEBUG
	print "There is no data to display.\n";
	$ret = 1;
	&exit_routine;
}

if ($DATA[0] eq -11) {
#	print "SnmInfo returned -11.\n";             #DEBUG
	print "The file specified is not a trace file.\n";
	$ret = 1;
	&exit_routine;
}

$lines = 0;
foreach (@DATA) {
	@COLUMNS = split /\s+/,$_,$BLANK_SEP_COLS;
	@MSG_RAW_DATA = split /\"/;
        $columns = 0;
	foreach (@COLUMNS) {
		$OUTPUT[$lines]{$columns} = $_;
		$columns += 1;
	}
	$OUTPUT[$lines]{$MSG_COL} = "\"".@MSG_RAW_DATA[1]."\"";
	$OUTPUT[$lines]{$RAW_DATA_COL} = @MSG_RAW_DATA[2];
	$lines += 1;
}

# If the user did not specify Format or specified --all print
#    out header line
if ((not defined $Format) || (defined $all)) {
	foreach (@ORDER) {
		$HEADER = $HEADER.$HEAD[$_];
	}
	print $HEADER."\n";
}

# Now for each line of data, we'll set up an output line with only the
#      data columns the user asked for
for ($k = 0; $k < $lines; $k++) {
	$LINE_OUT = "";      # Blank out output line

	# Now according to the order of the fields requested,
	#     we'll generate the output line with each column's
	#     format and the data for that column
	foreach (@ORDER) {
                # If no Format spec was passed or if --all was, we'll
		#     generate the output line with each field's format 
                #     and data for that field;  otherwise, we'll just 
                #     output the data
		#     separated by colons
		if ((not defined $Format) || (defined $all)) {
			$FIELD_OUT = sprintf "$FORMAT[$_]", $OUTPUT[$k]{$_};
			$LINE_OUT = $LINE_OUT.$FIELD_OUT;
		}
		else {
			# Is there a value to print?
			if ($OUTPUT[$k]{$_} ne " ") {
				if ($DEF_PROPS[$_] eq "details") {
					# If this field has a colon, we
					#   need to add quotes
					$check_colon = `echo $OUTPUT[$k]{$_} | /bin/grep ":"`;
					if ($check_colon ne "") {
						$LINE_OUT = $LINE_OUT."\"".$OUTPUT[$k]{$_}."\":";
					}
					else {
						$LINE_OUT = $LINE_OUT.$OUTPUT[$k]{$_}.":";
					}
				}
				else {
					$LINE_OUT = $LINE_OUT.$OUTPUT[$k]{$_}.":";
				}
			}
			else {
				# If not, just add a colon
				$LINE_OUT = $LINE_OUT.":";
			}
		}
	}
	print $LINE_OUT."\n";
}

$ret = 0;
$exit_routine;

